#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int			chile_stop = 0;
int			parent_run = 0;

void sig_chile_usr1(int signum)
{
	if(SIGUSR1 == signum)
	{
		chile_stop = !chile_stop;
	}
}

void sig_parent_usr2(int signum)
{
	if(SIGUSR2 == signum)
	{
		parent_run = !parent_run;
	}
}

#define chile_str "hello 111"
#define parent_str "hahaha"

int main(int argc, char **argv)
{
	int					pid = -1;
	int					pipe_chile[2];
	int					pipe_parent[2];
	int					rv = -1;
	char				buf[1024];


	signal(SIGUSR1, sig_chile_usr1);
	signal(SIGUSR2, sig_parent_usr2);

	if( pipe(pipe_parent) < 0)
	{
		printf(" pipe parent error \n");
		return -2;
	}
	if( pipe(pipe_chile) < 0)
	{
		printf("pipe chile error\n");
		return -3;
	}

	pid = fork();
	if(pid < 0)
	{
		printf(" fork error\n");
		return -4;
	}
	else if(pid == 0)
	{
		printf(" chile ok \n");

		close(pipe_chile[0]);
		close(pipe_parent[1]);

		write(pipe_chile[1], chile_str, strlen(chile_str));
		
		kill(getppid(), SIGUSR2);
		
		while(!chile_stop)
		{
			printf(" chile sleep :read \n");
			sleep(1);
		}

		memset(buf,0,sizeof(buf));
		read(pipe_parent[0], buf, sizeof(buf));

		printf("chile read ok : %s \n ", buf);

		return 0;

	}

	close(pipe_chile[1]);
	close(pipe_parent[0]);

	while(!parent_run)
	{
		printf("parent sleep :read \n");
		sleep(1);
	}

	memset(buf,0,sizeof(buf));
	read(pipe_chile[0], buf, sizeof(buf));

	strncat(buf, parent_str, strlen(parent_str));

	write(pipe_parent[1], buf, strlen(buf));

	kill(pid, SIGUSR1);
	
	printf(" parent weite succed\n");

	wait(&rv);

	return 0;


}


